﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LS.Common;
using LS.Entitys;
namespace LS.Cores
{
    /// <summary>
    /// 提供用户登录管理服务
    /// </summary>
    public class SysUserService : BaseService<SysUserEntity>, ISysUser
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public SysUserEntity Login(string name, string pwd)
        {
            string sql = "select top 1 * from sys_user where UserName = @UserName and UserPwd = @UserPwd";
            return SqlHelper.Query<SysUserEntity>(sql, new { UserName = name, UserPwd = pwd }).FirstOrDefault();
        }
        /// <summary>
        /// 用户是已存在
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public bool ExistAccount(string account)
        {
            string sql = "select top 1 id from sys_user where UserName = @UserName";
            return SqlHelper.Query<SysUserEntity>(sql, new { UserName = account }).Count() > 0;
        }
        public List<SysUserRoleEntity> GetRoleUser(string strwhere)
        {
            string sql = "select a.*,b.rolename From  sys_userrole  a left join sys_role b  on a.rolecode=b.rolecode ";
            if (!string.IsNullOrEmpty(strwhere))
            {
                sql += " where 1=1 " + strwhere;
            }
            return SqlHelper.Query<SysUserRoleEntity>(sql).ToList();
        }

        public int InsertUser(SysUserEntity model, List<SysUserRoleEntity> userroleList, List<SysOrganizeUserEntity> userorgList)
        {
            bool resulte = SqlHelper.ExecuteTranSql((con, tran) =>
            {
                int r = 0;
                try
                {
                    StringBuilder strsql = new StringBuilder();
                    strsql.Append("insert into sys_user(username,userpwd,RealName,Sex,Mobile,Email,UserType,isenable,createby,createdate,isdel,UserStatus,companyId,CompanyName,cardID,cardJustImg,cardBackImg) ");
                    strsql.Append(" values(@username,@userpwd,@realname,@sex,@mobile,@email,@usertype,@isenable,@createby,@createdate,@isdel,@UserStatus,@CompanyId,@CompanyName,@cardID,@cardJustImg,@cardBackImg)");
                    strsql.Append(" ;SELECT CAST(SCOPE_IDENTITY() as int)");
                    //r = SqlHelper.ExecuteCon(strsql.ToString(), model, tran, null, CommandType.Text, con);

                    int userid = SqlHelper.QueryIdentityCon(strsql.ToString(), model, tran, false, null, CommandType.Text, con);
                    if (userroleList != null && userroleList.Count > 0)
                    {
                        List<SysUserRoleEntity> listrole = new List<SysUserRoleEntity>();
                        userroleList.ForEach(a =>
                        {
                            listrole.Add(new SysUserRoleEntity { RoleCode = a.RoleCode, UserId = userid.ToString() });
                        });
                        StringBuilder strsqluserrole = new StringBuilder();
                        strsqluserrole.Append("insert into sys_userrole(Userid,rolecode) ");
                        strsqluserrole.Append(" values(@Userid,@rolecode)");
                        r = SqlHelper.ExecuteCon(strsqluserrole.ToString(), listrole, tran, null, CommandType.Text, con);
                    }
                    r = 1;

                }
                catch (Exception ex)
                {
                    Log4NetHelper.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType).Error(ex.Message);
                    r = 0;
                }

                return r;
            });
            return resulte ? 1 : 0;
        }

        public int UpdateUser(SysUserEntity model, List<SysUserRoleEntity> userroleList, List<SysOrganizeUserEntity> userorgList)
        {
            bool resulte = SqlHelper.ExecuteTranSql((con, tran) =>
            {
                int r = 0;
                try
                {
                    StringBuilder strsql = new StringBuilder();
                    strsql.Append("update sys_user set  ");
                    strsql.Append(" username=@username,userpwd=@userpwd,RealName=@realname,Sex=@sex,Mobile=@mobile,Email=@email,isenable=@isenable,UserType=@UserType,CompanyId=@CompanyId,CompanyName=@CompanyName,cardID=@cardID,cardJustImg=@cardJustImg,cardBackImg=@cardBackImg ");
                    strsql.Append(" where id=@id ");
                    r = SqlHelper.ExecuteCon(strsql.ToString(), model, tran, null, CommandType.Text, con);


                    if (userroleList != null && userroleList.Count > 0)
                    {
                        r = SqlHelper.ExecuteCon("delete from  sys_userrole where userid=@userid", new { userid = model.Id }, tran, null, CommandType.Text, con);

                        List<SysUserRoleEntity> listrole = new List<SysUserRoleEntity>();
                        userroleList.ForEach(a =>
                        {
                            listrole.Add(new SysUserRoleEntity { RoleCode = a.RoleCode, UserId = a.UserId });
                        });
                        StringBuilder strsqluserrole = new StringBuilder();
                        strsqluserrole.Append("insert into sys_userrole(userid,rolecode) ");
                        strsqluserrole.Append(" values(@userid,@rolecode)");
                        r = SqlHelper.ExecuteCon(strsqluserrole.ToString(), listrole, tran, null, CommandType.Text, con);

                    }
                    r = 1;
                }
                catch (Exception ex)
                {
                    Log4NetHelper.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType).Debug(ex.Message);
                    r = 0;
                }

                return r;
            });
            return resulte ? 1 : 0;
        }

        public int UpdateEnable(long id, int enable)
        {
            StringBuilder strsql = new StringBuilder();
            strsql.Append("update sys_user set ");
            strsql.Append(" isenable=@isenable");
            strsql.Append(" where id =@uid");
            int result = SqlHelper.Execute(strsql.ToString(), new { isenable = enable, uid = id });
            return result;
        }

        public int UpdatePwd(long id, string pwd)
        {
            StringBuilder strsql = new StringBuilder();
            strsql.Append("update sys_user set ");
            strsql.Append(" userpwd=@userpwd");
            strsql.Append(" where id =@Id");
            int result = SqlHelper.Execute(strsql.ToString(), new { userpwd = pwd, Id = id });
            return result;
        }

        public int UpdateAvater(long id, string avatar)
        {
            StringBuilder strsql = new StringBuilder();
            strsql.Append("update sys_user set ");
            strsql.Append(" Avatar=@Avatar");
            strsql.Append(" where id =@Id");

            return SqlHelper.Execute(strsql.ToString(), new { Avatar = avatar, Id = id });
        }

        public int AuditUser(string ids)
        {
            StringBuilder strsql = new StringBuilder();
            strsql.Append("update sys_user set ");
            strsql.Append(" userstatus=1 ");
            strsql.Append(" where id in( "+ ids + ")");

            return SqlHelper.Execute(strsql.ToString());
        }

        public int InsertAuditUser(List<SysUserRoleEntity> userroleList, List<SysOrganizeUserEntity> userorgList)
        {
            int r = 0;
            if (userroleList != null && userroleList.Count > 0)
            {
                List<long> listrole = new List<long>();
                userroleList.ForEach(a =>
                {
                    if (!listrole.Contains(Convert.ToInt64(a.UserId)))
                    {
                        listrole.Add(Convert.ToInt64(a.UserId));
                    }
                });
                SqlHelper.Execute(" delete from  sys_userrole where userid in ("+ string.Join(",", listrole) + ")");
                StringBuilder strsqluserrole = new StringBuilder();
                strsqluserrole.Append("insert into sys_userrole(userid,rolecode) ");
                strsqluserrole.Append(" values(@userid,@rolecode)");
                r = SqlHelper.Execute(strsqluserrole.ToString(), userroleList);

            }
            return r;
        }
    }
}